<?php
/**
 * Application model for Cake.
 *
 * This file is application-wide model file. You can put all
 * application-wide model-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Model
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Model', 'Model');

App::import('Component','Session');


 
/**
 * Application model for Cake.
 *
 * Add your application-wide methods in the class below, your models
 * will inherit them.
 *
 * @package       app.Model
 */
class AppModel extends Model {

	protected $fieldToUnset = array(
		'id', 'create_date', 'modify_date', 'created_by', 'change_password', 'password'
	);
	
	var $relations = array();
	
	protected $fields = array();
	
	protected static $changeLogData = array();
	
	/**
	 * requirnutie vsetkych modelov a potrebnych class
	 * 
	 * pride mi to divne ze to nie je automaticky naloadovane ale co uz
	 */
	protected function requireClasses() {
		require_once ('../Lib/Errors.php');
		require_once('Action.php');
		require_once('ChangeLog.php');
		require_once('Commission.php');
		require_once('DeletedItem.php');
		require_once('Market.php');
		require_once('Name.php');
		require_once('Person.php');
		require_once('PersonType.php');
		require_once('Transfer.php');
		require_once('User.php');
	}
	
	public function getItemType($table) {
		$itemTypes = array(
			'mnhis_action' => 'Akcia',
			'mnhis_commission' => 'Depozit',
			'mnhis_market' => 'Ponuka / dopyt',
			'mnhis_person' => 'Osoba',
			'mnhis_person_type' => 'Typ osoby',
			'mnhis_transfer' => 'Obrat',
			'mnhis_user' => 'Používateľ'
		);
		
		if (isset($itemTypes[$table])) {
			return $itemTypes[$table];
		}
		return '';
	}
	
	public function getFieldName($field) {
		if (isset($this->fields[$field]) && isset($this->fields[$field]['name'])) {
			return $this->fields[$field]['name'];
		}
		return '';
	}
	
	public function getFieldValue($field, $value) {
		if (isset($this->fields[$field]) && isset($this->fields[$field]['reference'])) {
			$modelName = $this->fields[$field]['reference']['model'];
			$fieldName = $this->fields[$field]['reference']['field'];
			$model = new $modelName();
			$conditions = array($modelName . '.id' => $value);
			$result = $model->find('first', array('fields' => array($fieldName), 'conditions' => $conditions));
			if ($result) {
				return $result[$modelName][$fieldName];
			} else {
				return $this->fields[$field]['reference']['default'];
			}
		} elseif (isset($this->fields[$field]) && isset($this->fields[$field]['evaluation'])) {
			if (isset($this->fields[$field]['evaluation'][$value])) {
				return $this->fields[$field]['evaluation'][$value];
			} else {
				return $this->fields[$field]['evaluation']['default'];
			}
		}
		return $value;
	}
	
	public function beforeSave($options = array()) {
		$this->requireClasses();
		
		parent::beforeSave($options);

		if ($this->id === FALSE || $this->id === NULL) {
			$this->data[$this->alias]['create_date'] = time();

			App::uses('CakeSession', 'Model/Datasource');
			$session = new CakeSession();
			$actualUser = $session->read('Auth.User');

			if ($actualUser['Person']['id']) {
				$this->data[$this->alias]['created_by'] = $actualUser['Person']['id'];
			}
			
			// changeLog old_value
			$oldValue = array();
		} else {
			// changeLog old_value
			$oldValue = $this->find('first', array('conditions' => array($this->alias . '.id' => $this->id)));
			$oldValue = $oldValue[$this->alias];
		}

		$this->data[$this->alias]['modify_date'] = time();
		
		if ($this->alias !== 'ChangeLog') {
			
			$newValue = array('id' => $this->id);
			$newValue = array_merge($newValue, $this->data[$this->alias]);
			
			$data['ChangeLog'] = array(
				'item_id' => $this->id,
				'table' => $this->table,
				'model' => $this->alias,
				'old_value' => serialize($oldValue),
				'new_value' => serialize($newValue),
			);
			
			foreach ($this->fieldToUnset as $fieldToUnset) {
				if (isset($oldValue[$fieldToUnset])) {
					unset($oldValue[$fieldToUnset]);
				}
				if (isset($newValue[$fieldToUnset])) {
					unset($newValue[$fieldToUnset]);
				}
			}
			
			$newDiff = array_diff_assoc($newValue, $oldValue);
			$oldDiff = array_diff_assoc($oldValue, $newValue);
			
			$data['ChangeLog']['old_diff'] = serialize($oldDiff);
			$data['ChangeLog']['new_diff'] = serialize($newDiff);
			
			self::$changeLogData = $data;
		}
		return TRUE;
	}

	public function afterSave($created) {
		if ($this->alias !== 'ChangeLog') {
			$data = self::$changeLogData;
			// idecko doplname len v case vytvorenia, lebo v case modifikovania v self::$changeLogData
			//  uz je nastavene, ale nie je v $this->data
			if ($created) {
				$data['ChangeLog']['item_id'] = $this->data[$this->alias]['id'];
			}
			$changeLog = new ChangeLog();
			$changeLog->save($data);
		}
	}
	
	/**
	 * kedze nechceme, aby zmazany item zanikol naveky, ulozime ho do specialnenj tabulky
	 */
	public function  beforeDelete($cascade = TRUE) {
		$this->requireClasses();
		
		$canDelete = TRUE;
		foreach ($this->relations as $modelName => $fields) {
			$model = new $modelName();
			foreach($fields as $field => $options) {
				$conditions = array($modelName . '.' . $field => $this->id);
				$result = $model->find('all', array('conditions' => $conditions));
				
				if ($result) {
					$canDelete = FALSE;
					$itemList = array();
					foreach ($result as $oneItem) {
						$itemList[] = '"' . $oneItem[$modelName][$options['field']] . '"';
					}
					
					if (count($itemList) == 1) {
						$message = str_replace('###PLACEHOLDER###', implode(', ', $itemList), $options['message_one']);
					} else {
						$message = str_replace('###PLACEHOLDER###', implode(', ', $itemList), $options['message_more']);
					}
					Errors::addError($message);
				}
			}
		}
		
		if ($canDelete === FALSE) {
			return FALSE;
		}
		
		$item = $this->read('*', $this->id);

		$data['DeletedItem'] = array(
			'deleted_id' => $this->id,
			'item' => serialize($item[$this->alias]),
			'table' => $this->table,
			'model' => $this->alias,
		);

		$deletedItem = new DeletedItem();
		$deletedItem->save($data);

		return parent::beforeDelete($cascade);
	}
}

?>